<?php

namespace App\Repositories\Eloquent\Acl;

use Auth, Hash, DB, Session;
use Illuminate\Container\Container as App;
use App\Repositories\Eloquent\Repository;

class StaffRepository extends Repository
{
    protected $username;

    /**
     * AdministratorRepository constructor.
     * @param App $app
     * @param AdministratorRepository $Admin
     */
    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    /**
     * 指定模型名称
     *
     * @return mixed
     */
    function model()
    {
        return 'App\Models\Acl\Staff';
    }


    public function index($query = '')
    {
        // 获取分页数据
        if (!$query) {
            $result = $this->model
                ->normal()
                ->orderBy('id', 'asc');
        } else {
            // 若有查询参数
            $result = $this->model
                ->where('name', 'like', "%$query%");
        }

        return $result;
    }
    

    public function show($id)
    {
        $staff = $this->find($id);
        if (!$staff) 
            return $this->responseFail(404);        
        return $staff;          
    }


    public function store($request)
    {
        $staff = $this->create([
            'username' => $request->username,
            'password' => Hash::make(DEFAULT_PASSWORD),
            'branch_id' => $request->branch,
            'status' => STATUS_NORMAL
        ]);
        
        if ($result = !!$staff) {
            $staff->assignRole($request->roles);
        }
        if( $result )
            return $this->responseSuccess('添加人员成功', $staff, route('system.staff.index'));

        return $this->responseFail(500,'添加人员失败');
    }


    public function renew($request, $id)
    {
        DB::beginTransaction();
        try {
            $result = $this->update([
                'username' => $request->username,
                'branch_id' => $request->branch,
                'status' => STATUS_NORMAL
            ], $id);

            $this->find($id)->syncRoles($request->roles);
            
            DB::commit();

            return $this->responseSuccess('更新人员信息成功', $this->find($id));

        } catch (Exception $e) {
            DB::rollback();
            return $this->responseFail(500,'更新人员信息失败');
        }
        
        
    }


    public function chgpwd($request, $id)
    {
        $staff = Auth('admin')->user();

        if($staff->id != $id)
            return $this->responseFail(500,'账号信息错误');

        if(!Hash::check($request->oldpwd, $staff->password))
            return $this->responseFail(500,'原密码不正确');

        if( strcmp($request->newpwd, $request->rnewpwd) !== 0)
            return $this->responseFail(500,'两次输入的密码不一致');

        $result = $this->update([
            'password' => Hash::make($request->newpwd),
        ], $id);

        if(!!$result)
            return $this->responseSuccess('密码更新成功', $this->find($id));

        return $this->responseFail(500,'密码更新失败');

    }

    /**
     * 用户登录
     *
     * @param $request
     * @return \Illuminate\Http\JsonResponse|mixed
     */
    public function login($request)
    {
        if($request->captcha != Session::get('captcha'))
            return $this->responseFail(405,'验证码不正确');

        // 判断用户使用什么字段登录
        $username = collect($request)->only(['username', 'mobile', 'email'])
            ->filter(function ($value, $key) {
                if ($value) {
                    $this->username = [$key => $value];
                }
                return !!$value;
            })->toArray();
            
        // 获取用户账号激活状态
        $active = $this->findBy($name = key($username), current($username));
        if (!$active['status'] && $active[$name]) {  // 若账号未激活
            return $this->responseFail(401, '禁止登陆');
        }
        // 合并验证数据
        $data = array_merge($username, ['password' => $request->password, 'status' => 1]);
        // 用户认证
        if (Auth::guard('admin')->attempt($data)) {            
            return $this->responseSuccess('登录成功', $request, '/');
        }
        return $this->responseFail(405, '用户名或密码错误');
    }

}